<template>
  <el-dialog title="Set Permission" :visible.sync="dialogVisible" width="500px">
    <div>
      <el-form label-position="top">
        <el-form-item label="Role" required>
          <el-select v-model="value" style="width: 100%">
            <el-option
                v-for="item in roleList"
                :key="item.roleId"
                :label="item.name"
                :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="dialogVisible = false">Cancel</el-button>
      <el-button size="small" type="primary" @click="submit">Ok</el-button>
    </span>
  </el-dialog>
</template>

<script>
import config from '@/utils/config'
import qs from 'qs'

export default {
  name: 'userSetRole',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array
    },
    userIsWhite: {
      type: Function
    },
    isAlaCarte: {
      type: Boolean
    },
    payUserRequest: Boolean
  },
  data () {
    return {
      value: [],
      roleList: [],
      assignRoleList: []
    }
  },
  computed: {
    dialogVisible: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    }
  },
  methods: {
    async getAssignRoleList () {
      let temp = []
      let roleList = this.$store.state.user.roleList
      roleList.forEach(it => {
        temp.push(it.id)
      })
      let params = qs.stringify(
        {
          roleId: temp
        },
        { arrayFormat: 'repeat' }
      )
      await this.$interface.um.getAssignRoleList(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.assignRoleList = res.data
      })
    },
    async getRoleList () {
      await this.getAssignRoleList()
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.system.getClientRoleListApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        let roleList = res.data
        let assignRoleList = this.assignRoleList
        let roleTemp = []
        let assignTemp = []
        let temp = []
        roleList.forEach(ii => {
          roleTemp.push({
            roleId: ii.roleId,
            name: ii.name
          })
        })
        assignRoleList.forEach(it => {
          assignTemp.push({
            roleId: it.assignId,
            name: ''
          })
        })
        if (assignTemp.length > 0) {
          temp = this._.intersectionBy(roleTemp, assignTemp, 'roleId')
        } else {
          temp = roleTemp
        }
        this.roleList = temp
      }).catch(() => { })
    },
    async submit () {
      if (!this.value) return this.$message.warning('Please selected Role')
      const isFreeRole = this._.intersection(config.freeUserRole, [this.value]).length > 0
      const userList = this.list.filter(item => {
        return !this.userIsWhite(item)  // white list
            && item.status !== 0 // disable status
            && (isFreeRole ? this._.intersection(item.roleIdList, config.freeUserRole).length === 0 : this._.intersection(item.roleIdList, config.freeUserRole).length > 0)
      })
      let params = {
        userIds: userList.map(item => item.id),
        status: config.freeUserRole.includes(this.value) ? 2 : 1
      }
      const { queryNumberByUsers } = this.$interface.pay
      const { data } = await queryNumberByUsers(params)
      const { dtoList } = data.data
      this.payUserParams = {
        bundleExtraUsersId: dtoList && dtoList.length > 0 ? dtoList[0].bundleExtraUsersId : null,
        userIdList: userList.map(item => item.id),
        type: params.status
      }
      if (data.data.dtoList && data.data.dtoList.length > 0 && !this.isAlaCarte) {
        this.$emit('update:dtoList', dtoList)
        this.$emit('update:userBillableVisible', true)
        this.$emit('update:userBillableType', String(params.status))
        this.$emit('update:userBillable', '5')
      } else {
        try {
          await this.updateUserRole()
          if (params.status === 1) {
            const { payUser } = this.$interface.pay
            payUser(this.payUserParams).then()
          }
          // eslint-disable-next-line no-empty
        } catch (e) { }
      }
    },
    async updateUserRole () {
      const ids = [this.value]
      const { updateUserRole } = this.$interface.pay
      let params = {
        sysRoleDTOList: []
      }
      if (this._.intersection([this.value], config.freeUserRole).length > 0 ) {
        const { alaCarteUpdate } = this.$interface.pay
        alaCarteUpdate({
          attendance: this.value.includes(config.attendanceOnlyId),
          userIds: this.list.map(item => item.id)
        })
      }
      this.list.map(item => {
        if (item.id !== this.$store.state.user.id) {
          ids.map(items => {
            params.sysRoleDTOList.push({
              userId: item.id,
              roleId: items
            })
          })
        }
      })
      const { data } = await updateUserRole(params)
      if (data.code === 0) {
        this.$emit('success')
        if (this.payUserRequest) {
          const { payUser } = this.$interface.pay
          payUser(this.payUserParams).finally(() => {
            this.$emit('update:payUserRequest', false)
          })
        }
      } else {
        this.$message.error(data.msg)
      }
      this.dialogVisible = false
    }
  },
  created () {
    this.getRoleList()
  }
}
</script>

<style scoped>

</style>
